use std::sync::{Arc, Mutex};
use serde::{Deserialize, Serialize};
use tokio::sync::OnceCell;

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Config {
    pub node: Option<String>,
    pub optional_node: Option<Vec<String>>,
}

static NODE: OnceCell<Arc<Mutex<Config>>> = OnceCell::const_new();

pub async fn init_config() {
    get_config().await;
}

pub async fn get_config() -> &'static Arc<Mutex<Config>> {
    NODE.get_or_init(|| async {
        let config = Config {
            node: Some("http://localhost:9208".to_string()),
            optional_node: Some(vec!["http://localhost:9200".to_string(),"http://localhost:9201".to_string(), "http://localhost:9208".to_string(),"http://localhost:39209".to_string()]),
        };
        Arc::new(Mutex::new(config))
    }).await
}

pub async fn get_node() -> String {
    let config = get_config().await;
    let config = config.lock().unwrap();
    config.node.clone().unwrap_or("http://localhost:9200".to_string())
}

pub async fn set_node(node:String) {
    let config = get_config().await;
    let mut config = config.lock().unwrap();
    config.node = Some(node);
}

pub async fn get_optional_node() -> Vec<String> {
    let config = get_config().await;
    let config = config.lock().unwrap();
    config.optional_node.clone().unwrap_or(Vec::new())
}